package com.yuns.web.sys.controller.system;

import com.yuns.jwt.JWTUtil;
import com.yuns.model.entity.SysPermission;
import com.yuns.model.entity.SysUser;
import com.yuns.model.service.SysPermissionService;
import com.yuns.util.ResultJson;
import com.yuns.web.sys.param.MetaParam;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @author clarck
 * @since 2018-07-26
 */
@RestController
@RequestMapping("/sysPermission")
@Api(tags = "权限")
public class SysPermissionController {


    @Autowired
    private SysPermissionService isys_permissionService;

    @PostMapping(value = "insert")
    public ResultJson insert(@RequestBody SysPermission model) {
        SysUser user = JWTUtil.getUser();
        model.setCreateBy(user.getId());
        model.setCreateTime(new Date());
        boolean flag = isys_permissionService.insert(model);
        if (flag) {
            return ResultJson.ok();
        } else {
            return ResultJson.error();
        }
    }

    @PutMapping(value = "up/{id}")
    public ResultJson update(@RequestBody SysPermission entity) {
        if (entity.getId() == null) {
            return ResultJson.error();
        }
        boolean flag = isys_permissionService.updateById(entity);

        if (flag) {
            return ResultJson.ok();
        } else {
            return ResultJson.error();
        }
    }


    @DeleteMapping(value = "delete/{id}")
    public ResultJson delete(@PathVariable("id") Integer id) {
        boolean flag = isys_permissionService.deleteById(id);
        if (flag) {
            return ResultJson.ok();
        } else {
            return ResultJson.error();
        }
    }


    /**
     * @return
     */
    @GetMapping(value = "findPermission")
    public ResultJson findPermission() throws UnsupportedEncodingException {
        Set<MetaParam> metaParams = isys_permissionService.findPermission();
        return ResultJson.ok(metaParams);
    }


    /**
     * @return
     */
    @GetMapping(value = "findTree")
    public ResultJson findTree() {
        List<SysPermission> sysPermissions = isys_permissionService.findTree(0);
        return ResultJson.ok(sysPermissions);
    }

    /**
     * @return
     */
    @GetMapping(value = "findTrees")
    public ResultJson findTrees() {
        List<SysPermission> sysPermissions = isys_permissionService.findTree();
        return ResultJson.ok(sysPermissions);
    }


}

